package com.kczd.fragment;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.UiSettings;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.overlayutil.DrivingRouteOverlay;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.route.BikingRouteResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.DrivingRouteResult;
import com.baidu.mapapi.search.route.IndoorRouteResult;
import com.baidu.mapapi.search.route.MassTransitRouteResult;
import com.baidu.mapapi.search.route.OnGetRoutePlanResultListener;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteResult;
import com.baidu.mapapi.search.route.WalkingRouteResult;
import com.baidu.mapapi.utils.DistanceUtil;
import com.baidu.navisdk.adapter.BNCommonSettingParam;
import com.baidu.navisdk.adapter.BNRoutePlanNode;
import com.baidu.navisdk.adapter.BNaviSettingManager;
import com.baidu.navisdk.adapter.BaiduNaviManager;
import com.kczd.activity.BNDemoGuideActivity;
import com.kczd.activity.SearchActivity;
import com.kczd.client.R;
import com.kczd.util.ClientIp;
import com.kczd.util.Common;
import com.kczd.util.NetRET;
import com.kczd.util.StringSaveUtil;
import com.swwx.paymax.PayResult;
import com.swwx.paymax.PaymaxCallback;
import com.swwx.paymax.PaymaxSDK;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * 首页
 */

public class PagerFragment extends Fragment  implements OnGetGeoCoderResultListener,PaymaxCallback {

    private final static String TAG ="PagerFragment.class";
    private View view;
    protected MapView mMapView;
    protected BaiduMap mBaiduMap;
    private TextView mChufa;
    /**************************************************
     * 定位模式
     */
    private MyLocationConfiguration.LocationMode mCurrentMode;
    public LocationClient mLocationClient = null;

    /**
     * 是否是第一次定位
     */
    private boolean isFirstLoc = false;
    /**
     * 定位坐标
     */
    private static double mlatitude;
    private static double mlongitude;
    private static double mlatitudend;
    private static double mlongitudend;
    /**
     * 反地理编码
     */
    private GeoCoder mSearch;
    public static List<Activity> activityList = new LinkedList<Activity>();

    /**************************************************
     * View
     */
    private Button btn_nowposition;
    private TextView mOrigin;//起点
    private TextView mTermain;//终点

    /**************************************************
     * 页面属性
     */

    SweetAlertDialog pDialog = null;
    private String address;
    private String city="新疆";
    String position = "";

    private double price;
    private LinearLayout mll;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.main_activity, null);
        initView();
        initMap();
        initLocation();// 初始化定位
        activityList.add(getActivity());
        String cacheokeys =StringSaveUtil.getCachedOkey(getActivity());
        if(cacheokeys!=null) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    addShowCar();//获取订单的状态
                }
            }).start();
        }
        return view;

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode){
            case 1:
                if(resultCode==getActivity().RESULT_OK){
                    address=data.getStringExtra("adress");
                    mTermain.setText(address);
                    // Geo搜索
                    mSearch.geocode(new GeoCodeOption().city(
                            city).address(address));
                    mChufa.setVisibility(View.VISIBLE);

                }
        }
    }


    private void initView() {

        mll= (LinearLayout) view.findViewById(R.id.linearLayout);
        // 初始化搜索模块，注册事件监听
        mSearch = GeoCoder.newInstance();
        mSearch.setOnGetGeoCodeResultListener(this);
        mChufa= (TextView) view.findViewById(R.id.chufa);
        mChufa.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                routType1();
                mChufa.setText("立即支付");
                mChufa.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Toast.makeText(getActivity(),"开始支付订单",Toast.LENGTH_SHORT).show();
                        new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE).setTitleText("提示")
                                .setContentText("支付金额为："+price)
                                .setCancelText("取消")
                                .setConfirmText("支付")
                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sDialog) {
                                        new Thread(new Runnable() {
                                            @Override
                                            public void run() {
                                                paymoney();
                                            }
                                        }).start();
                                        sDialog.cancel();
                                    }
                                }).showCancelButton(true)
                                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sDialog) {
                                        sDialog.cancel();
                                    }
                                }).show();
                    }
                });
            }
        });
        mOrigin= (TextView) view.findViewById(R.id.tv_origin);
        mTermain= (TextView) view.findViewById(R.id.tv_terminal);
        mTermain.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(getActivity(),SearchActivity.class);
                startActivityForResult(intent,1);
            }
        });
        btn_nowposition = (Button) view.findViewById(R.id.btn_nowposition);
        // 手动请求定位 按钮
        btn_nowposition.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                requestLocation();
            }
        });
    }


    private void initMap() {
        mMapView = (MapView) view.findViewById(R.id.bmapView);
        // 获取地图控制器，相当mvc模式， mapView用于显示，map用于控制，如旋转，大小、位置等
        mBaiduMap = mMapView.getMap();
        mMapView.removeViewAt(1); // 删除百度地图Logo

        mLocationClient = new LocationClient(this.getActivity()); // 声明LocationClient类
        mLocationClient.registerLocationListener(mListener); // 注册监听函数

        // 设置地图相关手势禁用
        UiSettings mUiSettings = mBaiduMap.getUiSettings();
        // 禁用旋转
        mUiSettings.setRotateGesturesEnabled(false);
        // 禁用俯视
        mUiSettings.setOverlookingGesturesEnabled(false);
        /**
         * 设置定位图层配置信息，只有先允许定位图层后设置定位图层配置信息才会生效 customMarker用户自定义定位图标
         * enableDirection是否允许显示方向信息 locationMode定位图层显示方式
         */
        // 定位图层显示方式
        mCurrentMode = MyLocationConfiguration.LocationMode.NORMAL;
        boolean enableDirection = true;// 设置允许显示方向
        BitmapDescriptor customMarker = BitmapDescriptorFactory.fromResource(R.drawable.dizhi);// 添加一个自定义图标（圆点）
        mBaiduMap.setMyLocationConfigeration(new MyLocationConfiguration(mCurrentMode, enableDirection, customMarker));
        // 开始定位
        mLocationClient.start();

        isFirstLoc = true;
    }

    @Override
    public void onResume() {
        super.onResume();
        // 在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if(okey!=null) {
            Timerhandler.postDelayed(runnable, 3000);//开启计时器
        }
        mMapView.onResume();
        if(position!=null) {
            mOrigin.setText(position);
        }
    }

    @Override
    public void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        // 开启定位
        mBaiduMap.setMyLocationEnabled(true);
        if (!mLocationClient.isStarted()) {
            mLocationClient.start();// 开启定位
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        // 在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        mMapView.onPause();
    }

    @Override
    public void onStop() {
        // TODO Auto-generated method stub
        super.onStop();
        mBaiduMap.setMyLocationEnabled(false);
        mLocationClient.stop();// 停止定位
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        // 退出时停止定位
        mLocationClient.stop();
        // 退出时关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);

        // activity 销毁时同时销毁地图控件
        mMapView.onDestroy();

        // 释放资源
        if (mSearch != null) {
            mSearch.destroy();
        }
        mMapView = null;
        getActivity().unregisterReceiver(receiver);
    }

    /**
     * 订单起点 -> 终点路径规划
     */
    private void routType1() {
        mBaiduMap.clear();
        // 线路规划：地图绘制订单起点到终点路径规划
        LatLng stapoint = new LatLng(mlatitude,mlongitude);
        List<PlanNode> linkNodes = new ArrayList<PlanNode>();
        LatLng endpoint = new LatLng(mlatitudend, mlongitudend);
        showBaiduMapDrivingNavi(stapoint, linkNodes, endpoint);
        int distance = (int) DistanceUtil.getDistance(stapoint, endpoint);
        //price=testMoney(distance/ 1000 );
        price=0.01;
        Toast.makeText(getActivity(), "总路程约：" + distance / 1000 + "km（公里）", Toast.LENGTH_LONG).show();
    }

    /**
     * 根据路程，计算费用
     */
    double totalPrice = 0.0;//定义打车费用
    double perPrice = 2.0;  //定义每公里单价计费
    int startPrice = 9;    //定义起步价
    int tax=1;    //定义燃油附加税
    private double testMoney(int distance)
    {
        if(distance >3) //判断公里数
            totalPrice = startPrice + (distance - 3) * perPrice + tax; //计算价钱
        else
            totalPrice = startPrice + tax;

        return totalPrice;
    }

    /**
     * 路径规划
     */
    RoutePlanSearch mSearchdriver = null;

    private void showBaiduMapDrivingNavi(LatLng Apoint, List<PlanNode> Bpoints, LatLng Cpoint) {
        mSearchdriver = RoutePlanSearch.newInstance();
        PlanNode stNode = PlanNode.withLocation(Apoint);
        List<PlanNode> linkNodes = new ArrayList<PlanNode>();
        linkNodes.addAll(Bpoints);
        PlanNode enNode = PlanNode.withLocation(Cpoint);
        mSearchdriver.drivingSearch(new DrivingRoutePlanOption().from(stNode).passBy(linkNodes).to(enNode)
                .policy(DrivingRoutePlanOption.DrivingPolicy.ECAR_FEE_FIRST));
        final SweetAlertDialog pDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("Loading");
        pDialog.setCancelable(false);
        pDialog.show();
        mSearchdriver.setOnGetRoutePlanResultListener(new OnGetRoutePlanResultListener() {

            @Override
            public void onGetWalkingRouteResult(WalkingRouteResult arg0) {
                // TODO Auto-generated method stub
            }

            @Override
            public void onGetTransitRouteResult(TransitRouteResult arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onGetMassTransitRouteResult(MassTransitRouteResult massTransitRouteResult) {

            }

            @Override
            public void onGetDrivingRouteResult(DrivingRouteResult result) {
                // 隐藏进度条
                pDialog.dismiss();
                // 在地图上绘制驾车路线
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    Toast.makeText(getActivity(), "抱歉，未找到路线规划结果", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (result.error == SearchResult.ERRORNO.AMBIGUOUS_ROURE_ADDR) {
                    Toast.makeText(getActivity(), "起终点或途经点地址有岐义", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (result.error == SearchResult.ERRORNO.AMBIGUOUS_KEYWORD) {
                    Toast.makeText(getActivity(), "检索词有岐义", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (result.error == SearchResult.ERRORNO.ST_EN_TOO_NEAR) {
                    Toast.makeText(getActivity(), "起终点太近", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (result.error == SearchResult.ERRORNO.NO_ERROR) {
                    DrivingRouteLine route = result.getRouteLines().get(0);
                    DrivingRouteOverlay overlay = new DrivingRouteOverlay(mBaiduMap);
                    mBaiduMap.setOnMarkerClickListener(overlay);
                    overlay.setData(route);
                    overlay.addToMap();
                    overlay.zoomToSpan();
                }
            }

            @Override
            public void onGetIndoorRouteResult(IndoorRouteResult indoorRouteResult) {

            }

            @Override
            public void onGetBikingRouteResult(BikingRouteResult bikingRouteResult) {

            }
        });
    }

    /**
     * 手动请求定位的方法
     */
    public void requestLocation() {
        LatLng ll = new LatLng(mlatitude, mlongitude);
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
        mBaiduMap.animateMapStatus(u);
    }

    BroadcastReceiver receiver=null;
    private void RegisterSDKCheckReceiver() {// 此方法用来检查接收到sdk
        receiver = new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
                String action = intent.getAction();
                // 判断是哪个action
                if (SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR.equals(action)) {
                    // 这里来Toast，创建一个base类来封装,需继承BaseFragment
                    Toast.makeText(getActivity(), "网络错误!", Toast.LENGTH_SHORT).show();

                } else if (SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR.equals(action)) {
                    Toast.makeText(getActivity(), "key验证失败!", Toast.LENGTH_SHORT).show();
                }

            }
        };
        IntentFilter filter = new IntentFilter();
        // 监听网络错误
        filter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
        // 监听百度地图SDK的key是否正确
        filter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);

        getActivity().registerReceiver(receiver, filter);
    }

    private void initLocation() {
        pDialog = new SweetAlertDialog(getActivity(), SweetAlertDialog.PROGRESS_TYPE);
        pDialog.getProgressHelper().setBarColor(Color.parseColor("#A5DC86"));
        pDialog.setTitleText("正在加载... ");
        pDialog.setCancelable(false);
        pDialog.show();

        RegisterSDKCheckReceiver();
        // 定位选项
        LocationClientOption option = new LocationClientOption();
        /**
         * coorType - 取值有3个： 返回国测局经纬度坐标系：gcj02 返回百度墨卡托坐标系 ：bd09 返回百度经纬度坐标系
         * ：bd09ll
         */
        option.setCoorType("bd09ll");
        // 设置是否需要地址信息，默认为无地址
        option.setIsNeedAddress(true);
        // 设置是否需要返回位置语义化信息，可以在BDLocation.getLocationDescribe()中得到数据，ex:"在天安门附近"，
        // 可以用作地址信息的补充
        // option.setIsNeedLocationDescribe(true);
        // 设置是否需要返回位置POI信息，可以在BDLocation.getPoiList()中得到数据
        // option.setIsNeedLocationPoiList(true);
        /**
         * 设置定位模式 Battery_Saving 低功耗模式 Device_Sensors 仅设备(Gps)模式 Hight_Accuracy
         * 高精度模式
         */
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        // 设置是否打开gps进行定位
        option.setOpenGps(true);
        // 设置扫描间隔，单位是毫秒 当<1000(1s)时，定时定位无效
        option.setScanSpan(1000);
        // 返回的定位结果包含手机机头的方向
        option.setNeedDeviceDirect(true);
        // 设置 LocationClientOption
        mLocationClient.setLocOption(option);
    }

    /*****
     *      定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    private BDLocationListener mListener = new BDLocationListener() {
        boolean bGetLocName = false;

        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (null != bdLocation && bdLocation.getLocType() != BDLocation.TypeServerError) {

                // 如果bdLocation为空或mapView销毁后不再处理新数据接收的位置
                if (bdLocation == null || mBaiduMap == null) {
                    return;
                }

                // 定位数据
                MyLocationData data = new MyLocationData.Builder()
                        // 定位精度bdLocation.getRadius()
                        .accuracy(bdLocation.getRadius())
                        // 此处设置开发者获取到的方向信息，顺时针0-360
                        .direction(bdLocation.getDirection())
                        // 经度
                        .latitude(bdLocation.getLatitude())
                        // 纬度
                        .longitude(bdLocation.getLongitude())
                        // 构建
                        .build();

                // 设置定位数据
                mBaiduMap.setMyLocationData(data);


                if (!bGetLocName) {
                    if (bdLocation.getCity() != null) {
                        bGetLocName = true;
                        position = bdLocation.getCity() + bdLocation.getDistrict() + bdLocation.getStreet();
                        mOrigin.setText(position);
                        Toast.makeText(getActivity(), "当前位置：" + position, Toast.LENGTH_SHORT).show();
                    }
                }

                mlatitude = bdLocation.getLatitude();
                mlongitude = bdLocation.getLongitude();

                // 是否是第一次定位
                if (isFirstLoc) {
                    pDialog.dismiss();
                    isFirstLoc = false;
                    LatLng ll = new LatLng(mlatitude, mlongitude);
                    MapStatusUpdate msu = MapStatusUpdateFactory.newLatLngZoom(ll, 18);
                    mBaiduMap.animateMapStatus(msu);

                }
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    };

//-----------------------------------------------------------------------------逆向地理编码
    /**
     * 换算为经纬度
     * @param result
     */
    @Override
    public void onGetGeoCodeResult(GeoCodeResult result) {
        if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
            mTermain.setText("请输入你终点...");
            Toast.makeText(getActivity(), "抱歉，未能找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        String strInfo = String.format("纬度：%f 经度：%f",
                result.getLocation().latitude, result.getLocation().longitude);
        mlatitudend=result.getLocation().latitude;
        mlongitudend=result.getLocation().longitude;
        //Toast.makeText(getActivity(), strInfo, Toast.LENGTH_LONG).show();
    }

    /**
     *换算为城市
     * @param reverseGeoCodeResult
     */
    @Override
    public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {

    }

//--------------------------------------------------------------------------------------------支付逻辑
    /**
     * 开始支付
     */
    String url = Common.net_addr +"itf/tx_pay.php";
    String callurl = Common.net_addr +"itf/tx_retrieve.php";
    private void paymoney()
    {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder()
                .add("ukey", Common.user.getUkey())
                .add("startPos",mOrigin.getText().toString())
                .add("start_lat", mlatitude+"")
                .add("start_lgt", mlongitude+"")
                .add("endPos", mTermain.getText().toString())
                .add("end_lat", mlatitudend+"")
                .add("end_lgt", mlongitudend+"")
                .add("amount", formateRate(price+""))
                .add("subject", "打车")
                .add("body", mOrigin.getText().toString()+"---"+ mTermain.getText().toString())
                .add("channel","alipay_app")
                .add("client_ip", ClientIp.getIPAddress(getActivity())+"")
                .build();

        Request request=new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();
        try {
            Response response=client.newCall(request).execute();
            String strResult=response.body().string();

            if(response.code() == 200) {
                Message msg = new Message();
                Bundle data = new Bundle();
                data.putString("ret_json", strResult);
                msg.setData(data);
                payhandle.sendMessage(msg);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private String id=null;
    private String okey=null;
    Handler payhandle = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e("val",val);
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonObject=null;
            try {
                jsonObject=new JSONObject(val);
                id=jsonObject.getString("id");
                okey=jsonObject.getString("order_no");
                StringSaveUtil.cachedOkey(getActivity(),okey);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            PaymaxSDK.pay(getActivity(),val,PagerFragment.this);

        }
    };

    public String formateRate(String rateStr){
        if(rateStr.indexOf(".") != -1){
            //获取小数点的位置
            int num = 0;
            num = rateStr.indexOf(".");

            //获取小数点后面的数字 是否有两位 不足两位补足两位
            String dianAfter = rateStr.substring(0,num+1);
            String afterData = rateStr.replace(dianAfter, "");
            if(afterData.length() < 2){
                afterData = afterData + "0" ;
            }else{
            }
            return rateStr.substring(0,num) + "." + afterData.substring(0,2);
        }else{
            if(rateStr == "1"){
                return "100";
            }else{
                return rateStr;
            }
        }
    }
    @Override
    public void onPayFinished(PayResult result) {

        switch (result.getCode()) {
            case PaymaxSDK.CODE_SUCCESS:
                Log.e("id", id);
                if (id != null) {
                    OkHttpClient okHttpClient = new OkHttpClient();
                    RequestBody requestBody = new FormBody.Builder()
                            .add("id", id)
                            .build();
                    Request request = new Request.Builder()
                            .url(callurl)
                            .post(requestBody)
                            .build();
                    try {
                        Response response = okHttpClient.newCall(request).execute();
                        if (response.code() == 200) {

                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                break;
        }
    }
    private Handler Timerhandler=new Handler();
    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            // TODO Auto-generated method stub
            new Thread(new Runnable() {
                @Override
                public void run() {
                    addShowCar();//获取订单的状态
                }
            }).start();
            Log.e(TAG,"请求服务器，给我司机的相关信息");
        }
    };
    /**
     * 获取订单的状态
     */
    String orderurl=  Common.net_addr +"itf/tx_get_order_status.php";
    public  void addShowCar(){
        String str="";
        if(okey==null)
        {
            str=StringSaveUtil.getCachedOkey(getActivity());
        }else{
            str=okey;
        }
        //获取订单状态
        OkHttpClient okHttpClient=new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder()
                .add("okey",str)
                .build();
        Log.e(TAG,"okey:"+okey);//订单的id
        Request request=new Request.Builder()
                .url(orderurl)
                .post(requestBody)
                .build();
        try {
            Response response=okHttpClient.newCall(request).execute();
            String strResult=response.body().string();
            Log.e("dreiver",strResult);
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            orderhandler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 获取订单状态
     */
    String status=null;
    Handler orderhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            Log.e(TAG,val);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(NetRET.NUM1.equals(jsonResult.getString("ret"))){
                    status=jsonResult.getString("ostatus");
                    pDialog.dismiss();
                    if(status.equals(Common.otype_0))
                    {
                        StringSaveUtil.cachedOkey(getActivity(),null);
                    }
                    if (status.equals(Common.otype_3)) {  //司机已抢单
                        pDialog.dismiss();
                        if (Common.user != null) {
                            new Thread() {
                                @Override
                                public void run() {
                                    getDkey();//获取司机的ID
                                }
                            }.start();
                        }
                        Toast.makeText(getActivity(), "有司机接单了", Toast.LENGTH_SHORT).show();
                    }
                    if(status.equals(Common.otype_4)){  //司机接上乘客
                        //添加终点的图标
                        initSdcardPath();

                        Toast.makeText(getActivity(), "司机接到乘客了", Toast.LENGTH_SHORT).show();
                    }
                    if(status.equals(Common.otype_5)){   //司机已完成订单
                        StringSaveUtil.cachedOkey(getActivity(),null);
                        Toast.makeText(getActivity(), "司机完成订单任务", Toast.LENGTH_SHORT).show();
                    }
                }else{
                    Toast.makeText(getActivity(), "获取位置失败", Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    };

    /**
     * 获取司机dkey
     */
    String taxiIDurl = Common.net_addr + "itf/tx_get_user_order.php";
    String taxiID="";
    public void getDkey() {
        //创建okHttpClient对象
        OkHttpClient client = new OkHttpClient();
        RequestBody requestBody = new FormBody.Builder()
                .add("utype", Common.utype)
                .add("ukey", Common.user.getUkey())
                .build();
        Request request = new Request.Builder()
                .url(taxiIDurl)
                .post(requestBody)
                .build();
        try {
            Response response = client.newCall(request).execute();
            String strResult = response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            dkeyhandler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    Handler dkeyhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG,"val的值是："+val);
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonResult;
            try {
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(NetRET.NUM1.equals(jsonResult.getString("ret"))){
                    JSONArray jsarrs =  jsonResult.getJSONArray("list_Arr");
                    for (int i = 0; i < jsarrs.length(); i++) {
                        JSONObject jso = jsarrs.getJSONObject(i);
                        taxiID=jso.getString("taxiID");
                        Log.e(TAG,"taxiID:"+taxiID);
                    }
                    getSijiLocation();//获取司机的经纬度
                }else{
                    Toast.makeText(getActivity(), jsonResult.getString("err"),
                            Toast.LENGTH_SHORT).show();
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    /**
     * //获取司机的经纬度
     */
    public void getSijiLocation(){

        new Thread(new Runnable() {
            @Override
            public void run() {
                getEndLocation();
            }
        }).start();
    }

    String dkeyurl=  Common.net_addr +"itf/tx_get_dache_driver_position.php";
    public void getEndLocation() {
        OkHttpClient okHttpClient=new OkHttpClient();
        RequestBody requestBody=new FormBody.Builder()
                .add("dkey",taxiID)
                .add("ukey",Common.user.getUkey())
                .add("ulat",mlatitude+"")
                .add("ulng",mlongitude+"")
                .build();
        Log.e(TAG,"dkey"+taxiID+"--"+"ukey"+Common.user.getUkey()+"--"+mlatitude+"---"+mlongitudend);
        Request request=new Request.Builder()
                .url(dkeyurl)
                .post(requestBody)
                .build();
        try {
            Response response=okHttpClient.newCall(request).execute();
            String strResult=response.body().string();
            Message msg = new Message();
            Bundle data = new Bundle();
            data.putString("ret_json", strResult);
            msg.setData(data);
            lohandler.sendMessage(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    Handler lohandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bundle data = msg.getData();
            String val = data.getString("ret_json");
            Log.e(TAG,"司机的经纬度："+val);
            val = val.substring(val.indexOf("{"),val.lastIndexOf("}")+1);
            JSONObject jsonResult;
            try {
                //{"ret":1,"err":"no error","lat":"34.296685","lng":"108.90598","distance":0.74}
                jsonResult = new JSONObject(val);
                // UI界面的更新等相关操作
                if(NetRET.NUM1.equals(jsonResult.getString("ret"))){
                    String endlat=jsonResult.getString("lat");
                    String endlng=jsonResult.getString("lng");
                    String distance=jsonResult.getString("distance");
                    //展示司机的位置
                    routType2(endlat,endlng);
                }else{
                    Toast.makeText(getActivity(), jsonResult.getString("err"),
                            Toast.LENGTH_SHORT).show();
                }

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };
    /**
     * 司机 -> 用户路径规划
     */
    private void routType2(String endlat,String endlng) {
        mBaiduMap.clear();
        // 线路规划：地图绘制司机到用户路径规划
        LatLng nowpoint = new LatLng(mlatitude, mlongitude);
        LatLng userpoint = new LatLng(Double.parseDouble(endlat),
                Double.parseDouble(endlng));
        //showBaiduMapDrivingNavi(nowpoint, new ArrayList<PlanNode>(), userpoint);
        addUserOverlay(userpoint);
    }
    /**
     * 初始化图层
     */
    public void addUserOverlay(LatLng latLng) {
        OverlayOptions overlayOptions = null;
        Marker marker = null;
        // 图标
        BitmapDescriptor customMarker = BitmapDescriptorFactory.fromResource(R.drawable.icon_car);// 添加一个自定义图标（圆点）
        overlayOptions = new MarkerOptions().position(latLng).icon(customMarker).zIndex(5);
        marker = (Marker) (mBaiduMap.addOverlay(overlayOptions));
        Bundle bundle = new Bundle();
        bundle.putSerializable("info", "用户当前位置");
        marker.setExtraInfo(bundle);
        // 将地图移到到最后一个经纬度位置
        MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(latLng);
        mBaiduMap.setMapStatus(u);
        int distance = (int) DistanceUtil.getDistance(latLng, new LatLng(mlatitude, mlongitude));
        Toast.makeText(getActivity(), "您与司机现在距离" + distance / 1000 + "公里", Toast.LENGTH_LONG).show();
    }

    /**
     * 导航HUD
     */
    private static final String APP_FOLDER_NAME = "BNSDKDemo";
    public static final String ROUTE_PLAN_NODE = "routePlanNode";
    private boolean hasInitSuccess = false;
    private String mSdcardPath = null;

    // private String authinfo = null;
    // ------导航开始---------
    private void initSdcardPath() {
        Log.e("kuaiche", "导航执行开始1");
        if (initDirs()) {
            initNaviPath();

        }
    }

    /**
     * 内部TTS播报状态回传handler
     */
    private Handler ttsHandler = new Handler() {
        public void handleMessage(Message msg) {
            int type = msg.what;
            switch (type) {
                case BaiduNaviManager.TTSPlayMsgType.PLAY_START_MSG: {
                    // showToastMsg("Handler : TTS play start");
                    break;
                }
                case BaiduNaviManager.TTSPlayMsgType.PLAY_END_MSG: {
                    // showToastMsg("Handler : TTS play end");
                    break;
                }
                default:
                    break;
            }
        }
    };

    /**
     * 内部TTS播报状态回调接口
     */
    private BaiduNaviManager.TTSPlayStateListener ttsPlayStateListener = new BaiduNaviManager.TTSPlayStateListener() {

        @Override
        public void playEnd() {
            // showToastMsg("TTSPlayStateListener : TTS play end");
        }

        @Override
        public void playStart() {
            // showToastMsg("TTSPlayStateListener : TTS play start");
        }
    };

    /**
     * 创建一个文件夹用于保存在路线导航过程中语音导航语音文件的缓存，防止用户再次开启同样的导航直接从缓存中读取即可
     *
     * @return
     */
    private boolean initDirs() {
        if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
            mSdcardPath = Environment.getExternalStorageDirectory().toString();
        } else {
            mSdcardPath = null;
        }
        if (mSdcardPath == null) {
            return false;
        }
        File file = new File(mSdcardPath, APP_FOLDER_NAME);
        if (!file.exists()) {
            try {
                file.mkdir();
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }
        // Toast.makeText(getActivity(), mSdcardPath, 0).show();
        return true;
    }

    private void initNaviPath() {

        // 初始化导航路线的导航引擎
        BaiduNaviManager.getInstance().init(getActivity(), mSdcardPath, APP_FOLDER_NAME, new BaiduNaviManager.NaviInitListener() {

            @Override
            public void onAuthResult(int status, String msg) {
//				String authinfo = null;
                if (status == 0) {
//					authinfo = "key校验成功!";
                } else {
//					authinfo = "key校验失败!"+msg;
                }
//				  Toast.makeText(getActivity(), authinfo,
//                          Toast.LENGTH_LONG).show();
            }

            @Override
            public void initSuccess() {
                hasInitSuccess = true;
                initSetting();
//				 Toast.makeText(getActivity(), "导航引擎初始化成功",
//				 Toast.LENGTH_LONG).show();
                new SweetAlertDialog(getActivity(), SweetAlertDialog.WARNING_TYPE).setTitleText("启动导航")
                        .setContentText("是否启动实时语音导航或路径？").setCancelText("查看路径").setConfirmText("启动导航")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                routeplanToNavi(new LatLng(mlatitude, mlongitude), new LatLng(mlatitudend, mlongitudend), mOrigin.getText().toString(), mTermain.getText().toString());
                                sDialog.dismissWithAnimation();
                            }
                        }).showCancelButton(true).setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        routType1();
                        sDialog.dismissWithAnimation();
                    }
                }).show();
            }

            @Override
            public void initStart() {
//				 Toast.makeText(getActivity(), "导航引擎初始化开始",
//				 Toast.LENGTH_LONG).show();
            }

            @Override
            public void initFailed() {
                Toast.makeText(getActivity(), "导航引擎初始化失败：安卓版本与HUD库不兼容", Toast.LENGTH_LONG).show();
            }
        }, null, ttsHandler, ttsPlayStateListener);
    }

    private void initSetting() {
        //BNaviSettingManager.setDayNightMode(BNaviSettingManager.DayNightMode.DAY_NIGHT_MODE_DAY);
        BNaviSettingManager
                .setShowTotalRoadConditionBar(BNaviSettingManager.PreViewRoadCondition.ROAD_CONDITION_BAR_SHOW_ON);
        BNaviSettingManager.setVoiceMode(BNaviSettingManager.VoiceMode.Veteran);
        // BNaviSettingManager.setPowerSaveMode(BNaviSettingManager.PowerSaveMode.DISABLE_MODE);
        BNaviSettingManager.setRealRoadCondition(BNaviSettingManager.RealRoadCondition.NAVI_ITS_ON);
        Bundle bundle = new Bundle();
        // 必须设置APPID，否则会静音
        bundle.putString(BNCommonSettingParam.TTS_APP_ID, "9354030");
        BNaviSettingManager.setNaviSdkParam(bundle);
    }

    private void routeplanToNavi(LatLng mySInfo, LatLng myEndInfo, String strStartPos, String strEndPos) {
        if (!hasInitSuccess) {
            Toast.makeText(getActivity(), "还未初始化!", Toast.LENGTH_SHORT).show();
            return;
        }
        BNRoutePlanNode startNode = new BNRoutePlanNode(mySInfo.longitude, mySInfo.latitude, strStartPos, null,
                BNRoutePlanNode.CoordinateType.BD09LL);// 根据得到的起点的信息创建起点节点
        BNRoutePlanNode endNode = new BNRoutePlanNode(myEndInfo.longitude, myEndInfo.latitude, strEndPos, null,
                BNRoutePlanNode.CoordinateType.BD09LL);// 根据得到的终点的信息创建终点节点
        if (startNode != null && endNode != null) {
            ArrayList<BNRoutePlanNode> list = new ArrayList<BNRoutePlanNode>();
            list.add(startNode);// 将起点和终点加入节点集合中
            list.add(endNode);
            BaiduNaviManager.getInstance().launchNavigator(getActivity(), list, 1, true, new MyRoutePlanListener(startNode));
        }
    }

    class MyRoutePlanListener implements BaiduNaviManager.RoutePlanListener {// 路线规划监听器接口类

        private BNRoutePlanNode mBNRoutePlanNode = null;

        public MyRoutePlanListener(BNRoutePlanNode node) {
            mBNRoutePlanNode = node;
        }

        @Override
        public void onJumpToNavigator() {
			   /*
             * 设置途径点以及resetEndNode会回调该接口
             */

            for (Activity ac : activityList) {

                if (ac.getClass().getName().endsWith("BNDemoGuideActivity")) {
                    return;
                }
            }
            Intent intent = new Intent(getActivity(), BNDemoGuideActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ROUTE_PLAN_NODE, (BNRoutePlanNode) mBNRoutePlanNode);
            intent.putExtras(bundle);
            startActivity(intent);
        }
        @Override
        public void onRoutePlanFailed() {
            Toast.makeText(getActivity(), "算路失败", Toast.LENGTH_SHORT).show();
        }

    }
}
